<template>
  <div>
    <div class="gva-search-box">
      <el-form ref="elSearchFormRef" :inline="true" :model="searchInfo" class="demo-form-inline"
        @keyup.enter="onSubmit">
        <el-form-item label="创建日期" prop="createdAtRange">
          <template #label>
            <span>
              创建日期
              <el-tooltip content="搜索范围是开始日期（包含）至结束日期（不包含）">
                <el-icon>
                  <QuestionFilled />
                </el-icon>
              </el-tooltip>
            </span>
          </template>

          <el-date-picker v-model="searchInfo.createdAtRange" class="!w-380px" type="datetimerange" range-separator="至"
            start-placeholder="开始时间" end-placeholder="结束时间" />
        </el-form-item>

        <el-form-item label="标题" prop="title">
          <el-input v-model="searchInfo.title" :clearable="true" placeholder="请输入标题" />
        </el-form-item>

        <el-form-item label="作者" prop="author">
          <el-input v-model="searchInfo.author" :clearable="true" placeholder="请输入作者" />
        </el-form-item>

        <el-form-item label="是否vip文章" prop="vip">
          <el-select v-model="searchInfo.vip" clearable placeholder="请选择">
            <el-option key="true" label="是" value="true"></el-option>
            <el-option key="false" label="否" value="false"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="上架状态" prop="status">
          <el-select v-model="searchInfo.status" clearable placeholder="请选择">
            <el-option key="true" label="已上架" value="true"></el-option>
            <el-option key="false" label="已下架" value="false"></el-option>
          </el-select>
        </el-form-item>

        <template v-if="showAllQuery">
          <!-- 将需要控制显示状态的查询条件添加到此范围内 -->
          <el-form-item label="分类" prop="category">
            <el-tree-select
              v-model="searchInfo.category"
              :data="category"
              check-strictly
              :props="{
                value:'ID',
                label:'name'
              }"
              :render-after-expand="false"
              />
          </el-form-item>

          <el-form-item label="标签" prop="tags">
            <el-select v-model="searchInfo.tags" clearable placeholder="请选择标签" filterable>
              <el-option v-for="(item, key) in dataSource.tags" :key="key" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>

          <el-form-item label="文章类型" prop="type">
            <el-select v-model="searchInfo.type" clearable placeholder="请选择文章类型" filterable>
              <el-option v-for="(item, key) in artTypeOptions" :key="key" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </template>

        <el-form-item>
          <el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
          <el-button icon="refresh" @click="onReset">重置</el-button>
          <el-button link type="primary" icon="arrow-down" @click="showAllQuery = true"
            v-if="!showAllQuery">展开</el-button>
          <el-button link type="primary" icon="arrow-up" @click="showAllQuery = false" v-else>收起</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button type="primary" icon="plus" @click="openDialog()">新增</el-button>
        <el-button icon="delete" style="margin-left: 10px;" :disabled="!multipleSelection.length"
          @click="onDelete">删除</el-button>

      </div>
      <el-table ref="multipleTable" style="width: 100%" tooltip-effect="dark" :data="tableData" row-key="ID"
        @selection-change="handleSelectionChange" @sort-change="sortChange">
        <el-table-column type="selection" width="55" />

        <el-table-column sortable align="left" label="日期" prop="CreatedAt" width="180">
          <template #default="scope">{{ formatDate(scope.row.CreatedAt) }}</template>
        </el-table-column>

        <el-table-column label="首图" prop="picture" width="200">
          <template #default="scope">
            <el-image preview-teleported style="width: 100px; height: 100px" :src="getUrl(scope.row.picture)"
                      fit="cover" />
          </template>
        </el-table-column>

        <el-table-column sortable align="left" label="标题" prop="title" width="120" />

        <el-table-column align="left" label="作者" prop="author" width="120">
        </el-table-column>
        <el-table-column align="left" label="文章类型" prop="type" width="120">
          <template #default="scope">
            {{ filterDict(scope.row.type, artTypeOptions) }}
          </template>
        </el-table-column>

        <el-table-column align="left" label="是否vip文章" prop="vip" width="120">
          <template #default="scope">{{ formatBoolean(scope.row.vip) }}</template>
        </el-table-column>

        <el-table-column align="left" label="上架状态" prop="status" width="120">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.status">已上架</el-tag>
            <el-tag type="info" v-else>未上架</el-tag>
          </template>
        </el-table-column>

        <el-table-column sortable align="left" label="售价（元）" prop="price" width="120" />

        <el-table-column align="left" label="分类" prop="category" width="200">
          <template #default="scope">
            <el-tree-select
              v-model="scope.row.category"
              :data="category"
              check-strictly
              disabled
              :render-after-expand="false"
              :props="{
                value:'ID',
                label:'name'
              }"
              />
          </template>
        </el-table-column>

        <el-table-column align="left" label="标签" prop="tags" width="120">
          <template #default="scope">
            <el-tag class="mr-1" v-for="(item, key) in filterDataSource(dataSource.tags, scope.row.tags)" :key="key">
              {{ item }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column align="left" label="简介" prop="intro" width="120" />



        <el-table-column sortable align="left" label="转发" prop="repost" width="120" />

        <el-table-column sortable align="left" label="浏览" prop="views" width="120" />

        <el-table-column align="left" label="操作" fixed="right" :min-width="appStore.operateMinWith">
          <template #default="scope">
            <el-button type="primary" link class="table-button" @click="getDetails(scope.row)"><el-icon
                style="margin-right: 5px">
                <InfoFilled />
              </el-icon>查看</el-button>
            <el-button type="primary" link icon="edit" class="table-button"
              @click="updateArticleFunc(scope.row)">编辑</el-button>
            <el-button type="primary" link icon="delete" @click="deleteRow(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination layout="total, sizes, prev, pager, next, jumper" :current-page="page" :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]" :total="total" @current-change="handleCurrentChange"
          @size-change="handleSizeChange" />
      </div>
    </div>
    <el-drawer destroy-on-close :size="appStore.drawerSize" v-model="dialogFormVisible" :show-close="false"
      :before-close="closeDialog">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg">{{ type === 'create' ? '新增' : '编辑' }}</span>
          <div>
            <el-button :loading="btnLoading" type="primary" @click="enterDialog">确 定</el-button>
            <el-button @click="closeDialog">取 消</el-button>
          </div>
        </div>
      </template>

      <el-form :model="formData" label-position="top" ref="elFormRef" :rules="rule" label-width="80px" :show-message="false">
        <el-row gutter="8">
          <el-col :span="18">
        <el-form-item label="标题:" prop="title">
          <el-input v-model="formData.title" :clearable="false" placeholder="请输入标题" />
        </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="文章类型:" prop="type">
              <el-tree-select v-model="formData.type" placeholder="请选择文章类型" :data="artTypeOptions" style="width:100%"
                              filterable check-strictly></el-tree-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row gutter="8">
          <el-col :span="5">
          <el-form-item label="首图:" prop="picture">
            <SelectImage v-model="formData.picture" file-type="image" />
          </el-form-item>
          </el-col>
          <el-col :span="19">
            <el-form-item label="简介:" prop="intro">
              <el-input type="textarea" rows="6" v-model="formData.intro" :clearable="true" placeholder="请输入简介" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row gutter="8">
          <el-col :span="6">
            <el-form-item label="作者:" prop="author">
              <el-input v-model="formData.author" :clearable="true" placeholder="请输入作者" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="售价（元）:" prop="price">
              <el-input v-model.number="formData.price" :clearable="true" placeholder="请输入售价（元）" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否vip文章:" prop="vip">
              <el-switch v-model="formData.vip" active-color="#13ce66" inactive-color="#ff4949" active-text="是"
                         inactive-text="否" clearable></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="上架状态:" prop="status">
              <el-switch v-model="formData.status" active-color="#13ce66" inactive-color="#ff4949" active-text="上架"
                         inactive-text="下架"></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row gutter="8">
          <el-col :span="6">
            <el-form-item label="分类:" prop="category">
              <el-tree-select
                v-model="formData.category"
                :data="category"
                check-strictly
                :render-after-expand="false"
                :props="{
                value:'ID',
                label:'name'
              }"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="标签:" prop="tags">
              <el-select multiple v-model="formData.tags" placeholder="请选择标签" filterable style="width:100%"
                         :clearable="false">
                <el-option v-for="(item, key) in dataSource.tags" :key="key" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item v-if="formData.type === 'richText'" label="内容:" prop="content">
          <RichEdit v-model="formData.content" />
        </el-form-item>
        <template v-else-if="formData.type === 'video'">
          <el-form-item label="视频:" prop="video">
            <SelectImage v-model="formData.video" file-type="video" />
          </el-form-item>
          <el-form-item label="使用要点:" prop="keyPoint">
            <div v-for="(pointItem, index) in formData.keyPoint" :key="index" class="flex mb-2 items-center w-full">
              <el-input v-model="formData.keyPoint[index]" placeholder="请输入使用要点" style="flex: 1; margin-right: 8px;" />
              <el-button type="danger" icon="close" @click="removeKeyPoint(index)" />
            </div>
            <el-button type="primary" style="width: 100%;" @click="addKeyPoint">+ 添加</el-button>
          </el-form-item>
          <el-form-item label="使用须知:" prop="instructions">
            <div v-for="(instructionItem, index) in formData.instructions" :key="index"  class="flex mb-2 items-center w-full">
              <el-input v-model="formData.instructions[index]" placeholder="请输入使用须知" style="flex: 1; margin-right: 8px;" />
              <el-button type="danger" icon="close" @click="removeInstruction(index)" />
            </div>
            <el-button type="primary" style="width: 100%;" @click="addInstruction">+ 添加</el-button>
          </el-form-item>
        </template>
        <el-form-item v-else label="音频:" prop="audio">
          <SelectFile v-model="formData.audio" />
        </el-form-item>

      </el-form>
    </el-drawer>

    <el-drawer destroy-on-close :size="appStore.drawerSize" v-model="detailShow" :show-close="true"
      :before-close="closeDetailShow" title="查看">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="标题">
          {{ detailForm.title }}
        </el-descriptions-item>
        <el-descriptions-item label="作者">
          <span>{{ detailForm.author }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="文章类型">
          {{ detailForm.type }}
        </el-descriptions-item>
        <el-descriptions-item label="是否vip文章">
          {{ detailForm.vip }}
        </el-descriptions-item>
        <el-descriptions-item label="上架状态">
          {{ detailForm.status }}
        </el-descriptions-item>
        <el-descriptions-item label="售价（元）">
          {{ detailForm.price }}
        </el-descriptions-item>
        <el-descriptions-item label="分类">
          <el-tree-select v-model="detailForm.category"
                          :data="category" check-strictly disabled
            :render-after-expand="false"
            :props="{
                value:'ID',
                label:'name'
              }"
          />
        </el-descriptions-item>
        <el-descriptions-item label="标签">
          <el-tag class="mr-1" v-for="(item, key) in filterDataSource(dataSource.tags, detailForm.tags)" :key="key">
            {{ item }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="首图">
          <el-image style="width: 50px; height: 50px" :preview-src-list="returnArrImg(detailForm.picture)"
            :src="getUrl(detailForm.picture)" fit="cover" />
        </el-descriptions-item>
        <el-descriptions-item label="简介">
          {{ detailForm.intro }}
        </el-descriptions-item>
        <el-descriptions-item label="音频">
          <div class="fileBtn" v-for="(item, index) in detailForm.audio" :key="index">
            <el-button type="primary" text bg @click="onDownloadFile(item.url)">
              <el-icon style="margin-right: 5px">
                <Download />
              </el-icon>
              {{ item.name }}
            </el-button>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="视频">
          {{ detailForm.video }}
        </el-descriptions-item>
        <el-descriptions-item label="内容">
          <RichView v-model="detailForm.content" />
        </el-descriptions-item>
        <el-descriptions-item label="使用要点">
          <ArrayCtrl v-model="detailForm.keyPoint" />
        </el-descriptions-item>
        <el-descriptions-item label="使用须知">
          <ArrayCtrl v-model="detailForm.instructions" />
        </el-descriptions-item>
        <el-descriptions-item label="转发">
          {{ detailForm.repost }}
        </el-descriptions-item>
      </el-descriptions>
    </el-drawer>

  </div>
</template>

<script setup>
import {
  getArticleDataSource,
  createArticle,
  deleteArticle,
  deleteArticleByIds,
  updateArticle,
  findArticle,
  getArticleList
} from '@/api/cms/article'

import {getCategoryList} from '@/api/cms/category.js'
import { getUrl } from '@/utils/image'
// 图片选择组件
import SelectImage from '@/components/selectImage/selectImage.vue'
// 富文本组件
import RichEdit from '@/components/richtext/rich-edit.vue'
import RichView from '@/components/richtext/rich-view.vue'
// 文件选择组件
import SelectFile from '@/components/selectFile/selectFile.vue'
// 数组控制组件
import ArrayCtrl from '@/components/arrayCtrl/arrayCtrl.vue'

// 全量引入格式化工具 请按需保留
import { getDictFunc, formatDate, formatBoolean, filterDict, filterDataSource, returnArrImg, onDownloadFile } from '@/utils/format'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive } from 'vue'
import { useAppStore } from "@/pinia"

defineOptions({
  name: 'Article'
})

// 提交按钮loading
const btnLoading = ref(false)
const appStore = useAppStore()

const category = ref([])

const getCategory = async () => {
  const res =  await getCategoryList({ page: 1, pageSize: 1000 })
  if (res.code === 0) {
    category.value = res.data
  }
}

getCategory()


// 控制更多查询条件显示/隐藏状态
const showAllQuery = ref(false)

// 自动化生成的字典（可能为空）以及字段
const artTypeOptions = ref([])
const formData = ref({
  title: '',
  author: '',
  type: 'richText',
  price: undefined,
  vip: false,
  status: false,
  category: undefined,
  audio: [],
  tags: [],
  video: "",
  picture: "",
  intro: '',
  keyPoint: [],
  instructions: [],
  content: '',
})
const dataSource = ref([])
const getDataSourceFunc = async () => {
  const res = await getArticleDataSource()
  if (res.code === 0) {
    dataSource.value = res.data
  }
}
getDataSourceFunc()



// 验证规则
const rule = reactive({
  title: [
    {
      required: true,
      message: '请输入标题',
      trigger: ['input', 'blur']
    },
    {
      whitespace: true,
      message: '不能只输入空格',
      trigger: ['input', 'blur']
    }
  ],
  content: [
    {
      validator: (_rule, value, callback) => {
        if (formData.value.type === 'richText') {
          const text = String(value || '')
            .replace(/<[^>]*>/g, '')
            .replace(/&nbsp;/g, ' ')
            .trim()
          if (!text) {
            callback(new Error('请填写内容'))
            return
          }
        }
        callback()
      },
      trigger: ['change', 'blur']
    }
  ],
  video: [
    {
      validator: (_rule, value, callback) => {
        if (formData.value.type === 'video' && (!value || value === '')) {
          callback(new Error('请上传视频'))
        } else {
          callback()
        }
      },
      trigger: ['change', 'blur']
    }
  ],
  audio: [
    {
      validator: (_rule, value, callback) => {
        if (formData.value.type === 'audio' && (!value || value.length === 0)) {
          callback(new Error('请上传音频'))
        } else {
          callback()
        }
      },
      trigger: ['change', 'blur']
    }
  ]
})

const elFormRef = ref()
const elSearchFormRef = ref()

// =========== 表格控制部分 ===========
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const searchInfo = ref({})
// 排序
const sortChange = ({ prop, order }) => {
  const sortMap = {
    CreatedAt: "created_at",
    ID: "id",
    title: 'title',
    price: 'price',
    repost: 'repost',
    views: 'views',
  }

  let sort = sortMap[prop]
  if (!sort) {
    sort = prop.replace(/[A-Z]/g, match => `_${match.toLowerCase()}`)
  }

  searchInfo.value.sort = sort
  searchInfo.value.order = order
  getTableData()
}
// 重置
const onReset = () => {
  searchInfo.value = {}
  getTableData()
}

// 搜索
const onSubmit = () => {
  elSearchFormRef.value?.validate(async (valid) => {
    if (!valid) return
    page.value = 1
    if (searchInfo.value.vip === "") {
      searchInfo.value.vip = null
    }
    getTableData()
  })
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

// 修改页面容量
const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

// 查询
const getTableData = async () => {
  const table = await getArticleList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}

getTableData()

// ============== 表格控制部分结束 ===============

// 获取需要的字典 可能为空 按需保留
const setOptions = async () => {
  artTypeOptions.value = await getDictFunc('artType')
}

// 获取需要的字典 可能为空 按需保留
setOptions()


// 多选数据
const multipleSelection = ref([])
// 多选
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 删除行
const deleteRow = (row) => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteArticleFunc(row)
  })
}

// 多选删除
const onDelete = async () => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const IDs = []
    if (multipleSelection.value.length === 0) {
      ElMessage({
        type: 'warning',
        message: '请选择要删除的数据'
      })
      return
    }
    multipleSelection.value &&
      multipleSelection.value.map(item => {
        IDs.push(item.ID)
      })
    const res = await deleteArticleByIds({ IDs })
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
      if (tableData.value.length === IDs.length && page.value > 1) {
        page.value--
      }
      getTableData()
    }
  })
}

// 行为控制标记（弹窗内部需要增还是改）
const type = ref('')

// 更新行
const updateArticleFunc = async (row) => {
  const res = await findArticle({ ID: row.ID })
  type.value = 'update'
  if (res.code === 0) {
    formData.value = res.data
    dialogFormVisible.value = true
  }
}


// 删除行
const deleteArticleFunc = async (row) => {
  const res = await deleteArticle({ ID: row.ID })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    if (tableData.value.length === 1 && page.value > 1) {
      page.value--
    }
    getTableData()
  }
}

// 弹窗控制标记
const dialogFormVisible = ref(false)

// 打开弹窗
const openDialog = () => {
  type.value = 'create'
  dialogFormVisible.value = true
}

// 关闭弹窗
const closeDialog = () => {
  dialogFormVisible.value = false
  formData.value = {
    title: '',
    author: '',
    type: 'richText',
    price: undefined,
    vip: false,
    status: false,
    category: undefined,
    audio: [],
    tags: [],
    video: "",
    picture: "",
    intro: '',
    keyPoint: [],
    instructions: [],
    content: '',
  }
}
// 弹窗确定
const enterDialog = async () => {
  btnLoading.value = true
  elFormRef.value?.validate(async (valid, fields) => {
    if (!valid) {
      btnLoading.value = false
      const first = fields && Object.values(fields)[0]
      const msg = Array.isArray(first) && first[0] && first[0].message ? first[0].message : '请完善必填项'
      ElMessageBox.alert(msg, '提示', { type: 'warning' })
      return
    }
    let res
    switch (type.value) {
      case 'create':
        res = await createArticle(formData.value)
        break
      case 'update':
        res = await updateArticle(formData.value)
        break
      default:
        res = await createArticle(formData.value)
        break
    }
    btnLoading.value = false
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '创建/更改成功'
      })
      closeDialog()
      getTableData()
    }
  })
}

const detailForm = ref({})

// 查看详情控制标记
const detailShow = ref(false)


// 打开详情弹窗
const openDetailShow = () => {
  detailShow.value = true
}


// 打开详情
const getDetails = async (row) => {
  // 打开弹窗
  const res = await findArticle({ ID: row.ID })
  if (res.code === 0) {
    detailForm.value = res.data
    openDetailShow()
  }
}


// 关闭详情弹窗
const closeDetailShow = () => {
  detailShow.value = false
  detailForm.value = {}
}

// 添加使用要点
const addKeyPoint = () => {
  formData.value.keyPoint.push('')
}

// 删除使用要点
const removeKeyPoint = (index) => {
  formData.value.keyPoint.splice(index, 1)
}

// 添加使用须知
const addInstruction = () => {
  formData.value.instructions.push('')
}

// 删除使用须知
const removeInstruction = (index) => {
  formData.value.instructions.splice(index, 1)
}

</script>

<style>
.file-list {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.fileBtn {
  margin-bottom: 10px;
}

.fileBtn:last-child {
  margin-bottom: 0;
}
</style>
